'use strict';

const path = require('path');

const fs = require('mz/fs');
const pump = require('mz-modules/pump');
const uuidv1 = require('uuid/v1')

const Controller = require('../../core/common');

class UploadsController extends Controller {

  async index() {

  }

  async show() {

  }

  async create() {
    const { ctx } = this;

    const { oss = '' } = ctx.request.body;

    if (!ctx.request.files) return ctx.throw(404, '请选择上传文件');
    const file = ctx.request.files[0];

    if (true) {
      const name = 'public/test/' + path.basename(file.filename);
      let result;
      try {
        // process file or upload to cloud storage
        result = await ctx.oss.put(name, file.filepath);
      } finally {
        // need to remove the tmp files
        await ctx.cleanupRequestFiles();
      }

      this.success({
        ...result,
        url: `${result.url}?x-oss-process=image/crop,${oss}`,
        name: `/${result.name}?x-oss-process=image/crop,${oss}`,
      });
    } else {

      const filename = uuidv1() + path.extname(file.filename).toLowerCase();
      this.ctx.helper.mkdirsSync('app/public/uploads');
      const targetPath = path.join(this.config.baseDir, 'app/public/uploads', filename);

      const source = fs.createReadStream(file.filepath);
      const target = fs.createWriteStream(targetPath);
      try {
        await pump(source, target);
        ctx.logger.warn('save %s to %s', file.filepath, targetPath);
      } finally {
        // delete those request tmp files
        await ctx.cleanupRequestFiles();
      }

      this.success({ url: '/public/uploads/' + filename });
    }

  }

}

module.exports = UploadsController;